<?php
	ob_end_clean();
	ob_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta http-equiv="Content-Script-Type" content="text/javascript" />
		<meta http-equiv="Content-Style-Type" content="text/css" />
	</head>
<body>
<?php
	require_once( '../system/smarty.inc' );
	require_once( '../system/mdao/Class_M_USER.php' );
	require_once( '../system/mdao/Class_M_OTHER.php' );
	require_once( '../system/Class_FILE_CSV.php' );
	require_once( '../system/Class_ERROR.php' );
	require_once( '../system/login.inc.php' );
	require_once( '../system/ecjp_m.php' );
	require_once( '../system/Class_PWD.php' );
	
	Class_PWD::valid_auth(ECJP_AUTH_USER,$login['staff_auth']);
	$docsv_import = FALSE;
	
	$csvf = Class_FILE_CSV::get_upload_file();

	if ($csvf) {
		// ロケール情報の変更
		$locale = setlocale(LC_ALL, 0);
		setlocale(LC_ALL,'ja_JP.UTF-8');
		
		$rowall = Class_FILE_CSV::fget_rows($csvf);
	
	if  (!empty($rowall)) {
		$col_heads = array(
			'login_id' ,   //ログインID
			'login_pwd',   //パスワード
			'user_name',   //ユーザー名
			'auth',        //権限
			'',            //権限名
			'ins_co_cd',   //折込会社コード
			'',            //折込会社名
			'electric_id',   //電波圏ID
			'',            //電波圏名
			'email',       //メールアドレス
			'login_ng',     //状態
			'memo',        //備考
			'',            //更新日時u_time
			'',            //登録日時c_time
			''             //更新者m_user_name
		);
		//$csvheads   =  array('login_id','login_pwd','user_name','auth','ins_co_cd','email','login_ng','memo');
		//$csvheadsjp =  array('ログインID','パスワード','ユーザ名','権限','折込会社','メールアドレス','状態','備考');
		$csvheads  = array();
		$col_index = array();
		foreach ($col_heads as $k => $v) {
			if (!empty($v)) {
				$csvheads[$k]  = $v;
				$col_index[$v] = $k;
			}
		} 
		
		$index_key1        = $col_index['login_id'];  //
		$index_pwd         = $col_index['login_pwd'];  //
		
		$index_auth        = $col_index['auth'];      //
		$col_auth          = $index_auth + 1;
		
		$index_electric_id   = $col_index['electric_id']; //
		$col_electric        = $index_electric_id + 1;
		
		$index_ins_co_cd   = $col_index['ins_co_cd']; //
		$col_ins_co        = $index_ins_co_cd + 1;
		$index_login_ng    = $col_index['login_ng']; //
		$col_login_ng      = $index_login_ng + 1;
		
		$ins_co_arr        = Class_M_OTHER::get_ins_co_array();
		$electric_arr      = Class_M_OTHER::get_electric_array();
		
		// 読み取り開始
		$err = new Class_ERROR("","");
		$dao = new Class_M_USER;
		$chk = $dao->get_checks();
		
		$ngline      = 0;
		$error_times = 0;
		$error_stop  = IMPORT_STOP_MAX_ERROR_TIMES;
		$errtext     = array();
		$isng        = FALSE;
		
		$linecount = count($rowall);
		$percentold = 100;
		foreach ($rowall as $line => $row) {
			$isng = FALSE;
			$percent = intval($line/$linecount * 100)."%";
			if  ( $percent != $percentold ) {
				Class_FILE_CSV::write_msg_checking_per( $percent ) ;
			}
			$percentold = $percent;
			//CSV内部重複不可チェック
			foreach ($rowall as $kk=>$vv) {
				if  ($line != $kk) {
					if ($row[$index_key1] == $vv[$index_key1]){
						$col = $index_key1 + 1;
						$isng = TRUE;
						$ngMsg_tmp[$line][] = "{$line}行と{$kk}行の{$col}列目の値重複不可。";
						$error_times++;
						if ($error_times > $error_stop) {
							break;
						}
					}
				}
			} 
			
			//一般チェック
			foreach ( $csvheads as $k=>$v ) {
				if ( isset($chk[$v]) ) {
					$msg =  $err->check( $rowall[$line][$k], $chk[$v] ); 
					if (!empty($msg)) {
						$isng = TRUE;
						$col  = $k+1;
						$ngMsg_tmp[$line][] = "{$line}行{$col}列目：{$msg}。";
						$error_times++;					
						if ($error_times > $error_stop) {
							break;
						}
					}
				}
			}
			//パスワード　転換
			$rowall[$line][$index_pwd]  = Class_PWD::do_encode($row[$index_pwd]);
			//権限存在チェック
			if ( ($row[$index_auth]*1 < 0) || ($row[$index_auth]*1 > 9) ) {
				$isng = TRUE;
				$error_times++;	
				$ngMsg_tmp[$line][] = "{$line}行{ $col_auth }列目：は0～8範囲内数値ではありません。";
			} 
			//折込会社存在チェック
			if ( $row[$index_auth] == '4' ) {
				if ( !empty($row[$index_ins_co_cd])){
					if (empty($ins_co_arr[$row[$index_ins_co_cd]])) {
						$isng = TRUE;
						$error_times++;
						$ngMsg_tmp[$line][] = "{$line}行{$col_ins_co}列目：折込会社コードは存在しません。";
					}
				} else {
						$isng = TRUE;
						$error_times++;
						$ngMsg_tmp[$line][] = "{$line}行{$col_ins_co}列目：権限は4の場合、折込会社コード入力必須です。";
				}
				
			} else {
				$rowall[$line][$index_ins_co_cd] = '0';
			}
			//電波圏チェック
			if ( $row[$index_auth] == '9' ) {
				if ( !empty($row[$index_electric_id])){
					if (empty($electric_arr[$row[$index_electric_id]])) {
						$isng = TRUE;
						$error_times++;
						$ngMsg_tmp[$line][] = "{$line}行{$col_electric}列目：電波圏コードは存在しません。";
					}
				} else {
						$isng = TRUE;
						$error_times++;
						$ngMsg_tmp[$line][] = "{$line}行{$col_electric}列目：権限は9の場合、電波圏コード入力必須です。";
				}
				
			} else {
				$rowall[$line][$index_electric_id] = '0';
			}
			
			//状態 チェック
			if ( !empty($row[$index_login_ng]) ) {
				if ( ($row[$index_login_ng]*1 < 0) || ($row[$index_login_ng]*1 > 10) ) {
				$isng = TRUE;
				$error_times++;	
				$ngMsg_tmp[$line][] = "{$line}行{$col_login_ng}列目：は0～9範囲内数値ではありません。";
			} 
			}
			
			if ( $isng ) {
				++$ngline;
				$errtext[$ngline] = $row;
				if ($error_times > $error_stop) {
					break;
				}
			}
		}

			if ($ngline > 0) {
				$errHtml = Class_FILE_CSV::format_msg($ngMsg_tmp);
				if ($error_times > $error_stop) {
					Class_FILE_CSV::write_msg_error( $errHtml ,$error_stop );	
				
				} else {
					Class_FILE_CSV::write_msg_error( $errHtml );	
				}
			} else {
				//DBへ更新
				try {
					$dao->begin_trans();
					$i = 0;
					$percent = "";
					$percentold = "";
					foreach ( $rowall as $k=>$v ) {
						$i++;
						$percent = intval($i/$line * 100)."%";
						if  ( $percent != $percentold ) {
							//sleep(1);
							Class_FILE_CSV::write_msg_doing( $percent ) ;
						}
						$percentold = $percent;
						$values    = array();
						/*
						foreach ( $v as $kk => $vv ) {
							$values[$csvheads[$kk]] = $vv;
						}
						*/
						
						foreach ( $csvheads as $kk => $vv ) {
							$values[$vv] = $v[$kk];
						}
						
						$keyvalues =  $values[$col_heads[$index_key1]];
						$where = sprintf(" {$col_heads[$index_key1]} = '%s'", $keyvalues );
						
						if ( $dao->exits( $where ) ) {
							if (!($dao->editbycol($keyvalues ,$values ,$col_heads[$index_key1] ))) {
								throw new  Exception("user_importdb更新エラー");
							}
						} else {
							if ( !( $dao->add($values ) ) ) {
								throw  new Exception("user_importdb更新エラー");
							}
						}
					}
					Class_FILE_CSV::write_msg_succed($line, "user");
					$dao->commit_trans();
					
				    //echo '<script language="javascript">parent.location.href = "user_import.php?pro=sucess"</script>';
				} catch (Exception $e) {
					
					$dao->rollback_trans();
					Class_FILE_CSV::write_msg_error( "DB Exceptionがありました。" );
				}
			} 
		}else {

		$errHtml = "CSVファイルエラー";
		Class_FILE_CSV::write_msg_error( $errHtml );
			
		}
		
		// ロケール情報の復元
		setlocale(LC_ALL, $locale);
	
	}else {

		$errHtml = "CSVファイルエラー";
		Class_FILE_CSV::write_msg_error( $errHtml );
	}
?>
</body>
	</himl>
	